package com.yuwei.base

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yuwei.base.entity.Res
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(){
    //通用的失败liveData
    val onFailed by lazy { MutableLiveData<Throwable>() }

    fun <T> executeNetwork(
        //suspend 挂起方法 i局势apiService里面的请求方法 ()-> 代表当前参数是一个方法
        s:suspend ()-> Res<T>,
        //成功的liveData 会把s的返回值中values添加到success中
        success:(T) ->Unit,
        //失败的LiveData，会把失败的信息(Throwable) 直接传递到通用的onFailed的postValue方法中
        failed :(Throwable) ->Unit = onFailed::postValue,
        okCode : Int = 200
    ){
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if(res.code == okCode){
                    success(res.data)
                }else{
                    failed(RuntimeException(res.message))
                }
            }catch (e : Exception){
                failed(e)
                Log.d("错误","${e.message}")
            }
        }
    }
}